// 后台
const express = require('express')
const http = require('http')

const app = express()

// 存储所有的客户端连接 socket
const clients = []

// 创建服务实例
const server = http.createServer(app)

// 在 HTTP 服务中集成 socket.io 用来提供 WebSocket 服务
const io = require('socket.io')(server)

// 通过 app 设置的都是 HTTP 资源请求处理
// 托管 public 目录中的静态资源
app.use(express.static('./public'))

// 通过 io 设置的都是 WebSocket 资源请求处理
io.on('connection', (socket) => {
  // clients.push(socket)

  console.log('a user connected')

  // 当客户端断开连接后触发该事件
  // socket.on('disconnect', () => {
  //   console.log('user disconnected')
  //   const index = clients.findIndex(c => c.socket === socket)
  //   if (index !== -1) {
  //     clients.splice(index, 1)
  //   }
  // })

  socket.on('nickname', nickname => {
    console.log(nickname)
    clients.push({
      // 名字: 连接信息
      nickname,
      socket
    })
    socket.emit('nickname', '注册成功')
  })

  socket.emit('chat-count', clients.length)

  socket.on('message', data => {
    const client = clients.find(c => c.socket === socket)
    // console.log(data)
    // 广播给所有的聊天室客户端
    io.emit('message', {
      isPrivate: false,
      nickname: client.nickname,
      message: data
    })
  })

  socket.on('private-message', data => {
    console.log('private-message', data)
    // 找到私聊用户，给它发送消息
    const privateUser = clients.find(c => c.nickname === data.privateUser)
    if (privateUser) {
      console.log(privateUser)
      privateUser.socket.emit('private-message', {
        nickname: clients.find(c => c.socket === socket).nickname,
        message: data.privateMessage
      })
    }
  })
})

server.listen(3000, () => {
  console.log(`Server is running at http://localhost:3000`)
})
